package com.leo.messagedigest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import static android.R.attr.y;

public class MainActivity extends AppCompatActivity {

    private String pw="正义";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void messageDigest(View view) {

        switch (view.getId()){
            case R.id.md5://32位
                String s = Md5("MD5", pw);
                Log.d("flag", "----------->得到的数据为messageDigest:md5" +s);
                break;
            case R.id.sha1://40位
                String x = Md5("SHA-1", pw);
                Log.d("flag", "----------->得到的数据为messageDigest:md5" +x);
                break;
        }

    }

    private String  Md5(String md5, String pw) {
        StringBuilder builder=new StringBuilder();
        try {//消息摘要的对象
            MessageDigest messageDigest=MessageDigest.getInstance(md5);

            //将运算的数据加载给messageDigest
            messageDigest.update(pw.getBytes());
            byte[] digest = messageDigest.digest();

            Log.d("flag", "----------->得到的数据为Md5:字节数字" +digest.length);
            for (int i = 0; i < digest.length; i++) {
         //       Log.d("flag", "----------->得到的数据为Md5:" +Integer.toBinaryString(digest[i]));

                //0xFF 二进制11111111

                int num = digest[i] & 0xFF;
                if (num<=0xF){
                    builder.append(0);
                }
                String res = Integer.toHexString(num);
                Log.d("flag", "----------->得到的数据为Md5:" +res);
                builder.append(res);
            }


        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }


        return builder.toString();
    }
}
